package com.example.im.ui.activity

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.ashokvarma.bottomnavigation.BottomNavigationBar
import com.ashokvarma.bottomnavigation.BottomNavigationItem
import com.ashokvarma.bottomnavigation.TextBadgeItem
import com.example.im.common.Enumerate
import com.example.im.R
import com.example.im.common.Constants
import com.example.im.common.ImApplication
import com.example.im.entity.EventBusData
import com.example.im.manager.ActivityCollector
import com.example.im.receiver.NetworkBroadcastReceiver
import com.example.im.ui.adapter.pager.MainPagerAdapter
import com.example.im.ui.fragment.MainChatFragment
import com.example.im.ui.fragment.MainFriendFragment
import com.example.im.ui.fragment.MainMineFragment
import com.example.im.mvp.presenter.MainPresenter
import com.example.im.mvp.view.IMainView
import com.example.im.ui.abstracts.AbstractBaseActivity
import com.example.im.utils.LogUtils
import io.reactivex.Observable
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.include_toolbar.*
import java.util.concurrent.TimeUnit

class MainActivity : AbstractBaseActivity<MainPresenter>(), IMainView,
    BottomNavigationBar.OnTabSelectedListener,
    ViewPager.OnPageChangeListener, NetworkBroadcastReceiver.OnNetStatusListener {

    override fun onAutomaticLoginStart(hint: String) {
        tv_system_hint.visibility = View.VISIBLE
        tv_system_hint.text = hint
        if (hint == "连接失败"){
            val dialog = AlertDialog.Builder(this)
                .setMessage("登录失败")
                .setPositiveButton("重新登录") { d, _ ->
                    d.cancel()
                    mPresenter!!.automaticLogin()
                }
                .setCancelable(false)
            dialog.show()
        }
    }

    override fun onAutomaticLoginEnd() {
        tv_system_hint.visibility = View.GONE
        tv_system_hint.text = null
    }

    private var pageAdapter: MainPagerAdapter? = null

    private var chatItem: TextBadgeItem = TextBadgeItem()
        .setBackgroundColorResource(R.color.red)
        .setHideOnSelect(false)
        .hide()

    private var friendItem: TextBadgeItem = TextBadgeItem()
        .setBackgroundColorResource(R.color.red)
        .setHideOnSelect(false)
        .hide()
    private var mineItem: TextBadgeItem = TextBadgeItem()
        .setBackgroundColorResource(R.color.red)
        .setHideOnSelect(false)
        .hide()

    private var networkBroadcastReceiver: NetworkBroadcastReceiver? = null

    override val layoutId: Int
        get() = R.layout.activity_main

    override fun initView() {
        tv_toolbar_title.text = "即时聊天"

        val fragments = mutableListOf<Fragment>(
            MainChatFragment(),
            MainFriendFragment(),
            MainMineFragment()
        )
        pageAdapter = MainPagerAdapter(supportFragmentManager, fragments)
        view_pager.addOnPageChangeListener((this))
        view_pager.setNoScroll(false)
        view_pager.offscreenPageLimit = fragments.size
        view_pager.adapter = pageAdapter

        bottom_navigation_bar
            .addItem(
                BottomNavigationItem(R.drawable.a1798, R.string.title_name_chat)
                    .setInActiveColorResource(R.color.gray_3)
                    .setInactiveIcon(ContextCompat.getDrawable(this, R.drawable.a1799))
                    .setBadgeItem(chatItem)
            )
            .addItem(
                BottomNavigationItem(R.drawable.a_1, R.string.title_name_friend)
                    .setInActiveColorResource(R.color.gray_3)
                    .setInactiveIcon(ContextCompat.getDrawable(this, R.drawable.a1742))
                    .setBadgeItem(friendItem)
            )
            .addItem(
                BottomNavigationItem(R.drawable.a1801, R.string.title_name_mime)
                    .setInActiveColorResource(R.color.gray_3)
                    .setInactiveIcon(ContextCompat.getDrawable(this, R.drawable.a1746))
                    .setBadgeItem(mineItem)
            )
            .setTabSelectedListener(this)
            .setFirstSelectedPosition(0)
            .initialise()

        //注册网络监听广播
        networkBroadcastReceiver = NetworkBroadcastReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(networkBroadcastReceiver, intentFilter)
        networkBroadcastReceiver!!.setOnNetStatusListener(this)

    }

    override fun initPresenter() {
        mPresenter = MainPresenter(this, this)
    }

    override fun onStart() {
        super.onStart()
        mPresenter!!.mainApplyPermissions(this)
        mPresenter!!.automaticLogin()
    }

    override fun isAuthenticated(isLogin: Boolean) {
        if (!isLogin) {
            startActivity(Intent(this, AccessActivity::class.java))
            finish()
        } else {
            mPresenter!!.automaticAddUser()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.top_nav_menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.action_add_friend -> {
                startActivity(Intent(this, UserActivity::class.java))
            }
            R.id.action_add_group -> {
                startActivity(Intent(this, RoomActivity::class.java))
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(networkBroadcastReceiver)
    }

    override fun onEventMainThread(eventBus: EventBusData<*>) {
        super.onEventMainThread(eventBus)
        when (eventBus.type ?: return) {
            Enumerate.Handle.list_chat -> setChatItem()
            else -> {
            }
        }
    }

    override fun onTabReselected(position: Int) {

    }

    override fun onTabUnselected(position: Int) {

    }

    override fun onTabSelected(position: Int) {
        view_pager.currentItem = position
    }

    override fun onPageScrollStateChanged(state: Int) {

    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

    }

    override fun onPageSelected(position: Int) {
        bottom_navigation_bar.selectTab(position)
    }

    override fun onNetChange(netStatus: Boolean) {
        if (netStatus) {
            //IMConnection.instance!!.reconnect()
        }
    }


    private fun setChatItem(): TextBadgeItem? {
        return when (val count = ImApplication.appDatabase().chatRecordEntireDao().count()) {
            0 -> chatItem.hide()
            else -> {
                if (chatItem.isHidden)
                    chatItem.show()
                chatItem.setText(
                    if (count > 1000) "···" else count.toString()
                )
            }
        }
    }

}
